import { FMVCS } from "../../fgui/fmvc/FMVCS";
import { GlobalEvent } from "../global/Global";
import EventSystem from "../../core/EventSystem";
import PlayerCtrl from "../player/PlayerCtrl";
import LevelChooseCtrl from "./LevelChooseCtrl";

/** 关卡选择界面 */
export default class LevelChooseView extends FMVCS.FView {
    itemList: fgui.GList = null;
    clickHandlers() {
        return [
            [this._views[`btnBack`], this.onBtnBack, this]
        ]
    }

    onBtnBack() {
        EventSystem.emit(GlobalEvent.UIListenID.UI_HomeView_Open);
        this.onClose();
    }

    onOpenCallBack() {
        this.initList();
    }

    initList() {
        if (this.itemList) return;
        this.itemList = this._views[`chooseList`].asList;
        this.itemList.setVirtual();
        this.itemList.itemRenderer = this.onItemRender.bind(this);
        this.itemList.numItems = Object.keys(LevelChooseCtrl.data.config).length;
    }

    onItemRender(index: number, obj: fgui.GObject) {
        let item = obj.asButton;
        item.onClick(this.onItemClick, this);
        let img = item.getChild(`imgLevel`).asImage;
        item.data = index;
        img.icon = fgui.UIPackage.getItemURL("Common", `${index}`);

        let isLock = index > PlayerCtrl.data.vo.maxLevel;
        let lockC = item.getController(`lock`);
        lockC.selectedIndex = isLock ? 1 : 0;
    }

    onItemClick(event: fgui.Event) {
        let target = event.currentTarget.$gobj;
        let level = target.data;
        let isLock = level > PlayerCtrl.data.vo.maxLevel;
        if(isLock){
            EventSystem.emit(GlobalEvent.UIListenID.UI_ShowTips, `关卡未解锁!`);
        }else{
            EventSystem.emit(GlobalEvent.UIListenID.UI_LevelChoose, level);
            this.onClose();
        }
    }
}